from fastapi import APIRouter, Depends
from pydantic import BaseModel
from lib.database import get_db
from entity.user import SysUser
from sqlalchemy import desc
# api定义
# get:路径参数、查询参数； post：formData, json
user_api = APIRouter(prefix="/api/user") 

@user_api.post("/add")
def addUser(username:str, role:str="user", db=Depends(get_db)):
    data = {
        "username":username,
        "password":"123456",
        "role":role
    }
    try:
        user = SysUser(**data)
        db.add(user)
        db.commit()
        return {"code":200, "msg":"添加成功"}
    except Exception as e:
        return {"code":500, "msg":str(e)}

@user_api.post("/del")
def addUser(user_id:int, db=Depends(get_db)):
    
    try:
        r = db.query(SysUser).filter(SysUser.id == user_id).delete()
        db.commit()
        return {"code":200, "msg":"删除成功"}
    except Exception as e:
        return {"code":500, "msg":str(e)}

@user_api.post("/edit")
def addUser(user_id:int, username:str, db=Depends(get_db)):
    data={
        "username":username
    }
    try:
        r = db.query(SysUser).filter(SysUser.id == user_id).update(data)
        db.commit()
        return {"code":200, "msg":"修改成功"}
    except Exception as e:
        return {"code":500, "msg":str(e)}

@user_api.get("/search")
def addUser(db=Depends(get_db)):
    where = {
        "username":"test3"
    }
    users = db.query(SysUser).filter_by(**where).all()
    return users